package com.budwk.app.util;

import com.aspose.words.Document;
import com.aspose.words.ImportFormatMode;
import com.aspose.words.License;
import com.aspose.words.SaveFormat;
import com.budwk.app.ocr_general.PathBean;
import fr.opensagres.poi.xwpf.converter.pdf.PdfConverter;
import fr.opensagres.poi.xwpf.converter.pdf.PdfOptions;
import nl.basjes.shaded.org.springframework.core.io.ClassPathResource;
import org.apache.poi.xwpf.usermodel.XWPFDocument;

import java.io.*;

public class WordTest {

    //  private static boolean license = false;

    public static void main(String[] arc) {
        // wordToPdf();
    }

    public static PathBean wordToPdfLibre(String wordUrl, String pdfUrl) {
        PathBean pathBean = null;
        try {
            LibreOfficeAndJodconverter.init();
            pathBean = LibreOfficeAndJodconverter.doDocToFdpLibreOne(wordUrl, pdfUrl);
            LibreOfficeAndJodconverter.desory();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        return pathBean;
    }

    public static void wordToPdfTest(String wordpath, String pdfpath) {
        FileInputStream fileInputStream = null;
        try {
            //指定Word文件
            fileInputStream = new FileInputStream(wordpath);
            XWPFDocument xwpfDocument = new XWPFDocument(fileInputStream);

            //指定导出的PDF目录
            FileOutputStream fileOutputStream = new FileOutputStream(pdfpath);
            PdfOptions pdfOptions = PdfOptions.create();

            //执行转换
            PdfConverter.getInstance().convert(xwpfDocument, fileOutputStream, pdfOptions);

            //关闭流
            fileInputStream.close();
            fileOutputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void wordToPdf(String wordpath, String pdfpath) {
        FileOutputStream os = null;
        try {
            // 凭证 不然切换后有水印
            InputStream is = new ClassPathResource("/license.xml").getInputStream();
            License aposeLic = new License();
            aposeLic.setLicense(is);
            //生成一个空的PDF文件
            File file = new File(pdfpath);
            os = new FileOutputStream(file);
            //要转换的word文件
            Document doc = new Document(wordpath);
            //doc.appendDocument(doc, ImportFormatMode.USE_DESTINATION_STYLES);//保留样式
            Document document = new Document();//新建一个空白pdf文档
            document.removeAllChildren();
            document.appendDocument(doc, ImportFormatMode.USE_DESTINATION_STYLES);//保留样式
            document.save(os, SaveFormat.PDF);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("word转pdf失败");
        } finally {
            if (os != null) {
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
